/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.comet.tapestry.services;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.func.F;
import org.apache.tapestry5.func.Flow;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.services.SymbolSource;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.services.javascript.JavaScriptStack;
import org.apache.tapestry5.services.javascript.StylesheetLink;

public class CometJavaScriptStack implements JavaScriptStack {
	
	private final SymbolSource symbolSource;
	
	private final AssetSource assetSource;
	
	private final List<Asset> javaScriptStack;
	
	private static final String ROOT = "${comet.assets}/js/";
	
	private static final String[] COMET_JAVASCRIPT = new String[] {
		ROOT + "json2.js",
		ROOT + "cometd.js",
		ROOT + "jquery.cometd.js"
	};
	
	public CometJavaScriptStack(
	          SymbolSource symbolSource,
	          AssetSource assetSource) {
		
	    this.symbolSource = symbolSource;
	    this.assetSource = assetSource;
	    this.javaScriptStack = convertToAssets(COMET_JAVASCRIPT);
	}	

	@Override
	public List<String> getStacks() {
		List<String> stacks = new ArrayList<>(1);
		stacks.add(InternalConstants.CORE_STACK_NAME);
		return stacks;
	}

	@Override
	public List<Asset> getJavaScriptLibraries() {
		return createStack(javaScriptStack).toList();
	}

	@Override
	public List<StylesheetLink> getStylesheets() {
		return Collections.emptyList();
	}

	@Override
	public String getInitialization() {
		return null;
	}
	
	private List<Asset> convertToAssets(String[] paths) {
	    List<Asset> assets = CollectionFactory.newList();
	
	    for (String path : paths) {
	      assets.add(expand(path, null));
	    }
	
	    return Collections.unmodifiableList(assets);
	}
	
	private Asset expand(String path, Locale locale) {
	    String expanded = symbolSource.expandSymbols(path);
	
	    return assetSource.getAsset(null, expanded, locale);
	}
	
	private static Flow<Asset> createStack(List<Asset> stack, Asset... assets) {
		return F.flow(stack).append(assets);
	}	

}
